// pages/team/index/index.js
import api from '../../../api/index';
import IMService from '../../../static/lib/imservice.js';
import store from "../../../store/index";

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pageSize: 100,
    pageNum: 1,
    teams: [],
    player: [],
    statusList: [
      '队员招募',
      "寻找团队"
    ],
    activeIndex: false,
    show: true,
    // 选择哪个比赛，进行分页展示
    option1: [], // 所有比赛名称
    value1: 0,
    contestIndex: 0, // 要展示哪个比赛
    flag: 1, // 判断是否是  更多  里面的选项
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const contestAllOptions = [];
    this.teamList();
    // 渲染所有比赛到 顶部选择器 
    for (let i = 0; i <= store.contestList.length; i++) {
      if (store.contestList.length == i) {
        contestAllOptions.push({
          text: "更多",
          value: i
        })
      } else {
        let textValue = store.contestList[i].name;
        let Value = i;
        contestAllOptions.push({
          text: textValue,
          value: Value
        })
      }

    }
    this.setData({
      option1: contestAllOptions
    })
    
    // this.publish()
  },

  teamList: async function () {
    return new Promise((reslove, reject) => {
      const t1 = this.list()
      const t2 = this.list2()
      reslove({ t1, t2 })
    })

  },
  list: async function () {
    var pageSize = this.data.pageSize
    var pageNum = this.data.pageNum
    var status = "need"
    var type = "all"
    var params = { status, type, pageSize, pageNum }
    return new Promise((reslove, reject) => {
      api.team.list(params).then(res => {
        console.log("队员招募的全部：")
        console.log(res.result.data.list);
        store.zudui.findPersonAll = res.result.data.list;
        console.log(this.data.option1);
        console.log(this.data.option1[this.data.contestIndex].text);
        let List = [];
        List = res.result.data.list.filter((item) => {
          // console.log(item);
          if (item.contestName === this.data.option1[this.data.contestIndex].text)
            return true;
          else
            return false;
        })
        
        // 筛选出跟选择项一样的
        console.log(List);


        this.setData({
          teams: List
        }, () => {
          this.flashComp()
          reslove(res)
        })

      })
    })

  },
  list2: async function () {
    var pageSize = this.data.pageSize
    var pageNum = this.data.pageNum
    var status = "need"
    var type = "all"
    var params = { status, type, pageSize, pageNum }
    return new Promise((reslove, reject) => {
      api.player.list(params).then(res => {
        console.log("寻找团队的全部：");
        console.log(res.result.data.list);
        store.zudui.findTeamAll = res.result.data.list;
        let List = [];
        List = res.result.data.list.filter((item) => {
          // console.log(item);
          if (item.contestName === this.data.option1[this.data.contestIndex].text)
            return true;
          else
            return false;
        })
        this.setData({
          player: List
        }, () => {
          this.flashComp()
          reslove(res)
        })
      })
    })

  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading()
    console.log('下拉刷新');
    this.teamList();
    this.selectContest({
      detail: this.data.contestIndex
    });
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  onShow: function () {
    //this.teamList()
    this.getCurr()
  },


  // 选择要看哪个比赛
  selectContest(options) {
    console.log(options);
    this.setData({
      contestIndex: options.detail
    })
    console.log(this.data.contestIndex);

    let pageSize = this.data.pageSize
    let pageNum = this.data.pageNum
    let status = "need"
    let type = "all"
    let params = { status, type, pageSize, pageNum }

    // 队员招募 的选择展示
    api.team.list(params).then(res => {
      let List = [];
      List = res.result.data.list.filter((item) => {
        // console.log(item);
        if (item.contestName === this.data.option1[this.data.contestIndex].text)
          return true;
        else
          return false;
      })

      // console.log(store.contestList);
      console.log("队员招募更多选择前，，应该是空的--------------------------")
      console.log(List)
      // 更多这个选项，List此时是空的，所以可以再进行一次filter过滤出
      if (this.data.option1[this.data.contestIndex].text === "更多") {
        // console.log(res.result.data.list)
        console.log("更多")
        List = res.result.data.list.filter((item) => {
          // console.log(item.contestName);
          // console.log(store.contestList);
          for(let i = 0; i < store.contestList.length; i++) {
            if (item.contestName === store.contestList[i].name) {
              this.data.flag = 0; // 不是  更多 选项里面的， 不用返回
              break;
            } else {
              this.data.flag = 1;
            }
          }

          if (this.data.flag == 0)
            return false;
          else
            return true;
        })
      }
      console.log("更多选择后，，应该有数据了--------------------------")
      console.log(List)

      this.setData({
        teams: List
      })
    })

    // 寻找团队 的选择展示
    api.player.list(params).then(res => {
      let List2 = [];
      List2 = res.result.data.list.filter((item) => {
        // console.log(item);
        if (item.contestName === this.data.option1[this.data.contestIndex].text)
          return true;
        else
          return false;
      })

      // console.log(store.contestList);

      console.log("寻找团队更多选择前，，应该是空的--------------------------")
      console.log(List2)
      //更多这个选项，List此时是空的，所以可以再进行一次filter过滤出
      if (this.data.option1[this.data.contestIndex].text === "更多") {
        console.log("更多")
        List2 = res.result.data.list.filter((item) => {
          // console.log(item);
          
          for(let i = 0; i < store.contestList.length; i++) {
            if (item.contestName === store.contestList[i].name) {
              this.data.flag = 0; // 不是  更多 选项里面的， 不用返回
              break;
            } else {
              this.data.flag = 1;
            }
          }
          if (this.data.flag == 0)
            return false;
          else
            return true;
        })
      }
      console.log("更多选择后，，应该有数据了--------------------------")
      console.log(List2)

      this.setData({
        player: List2
      })
    })

  },

  getCurr: async function () {
    var currentUser = {
      uuid: app.globalData.openid
    }
    app.globalData.imService = new IMService(wx.im);
    app.globalData.imService.connectIM(currentUser);
    if (wx.im.getStatus() === 'disconnected') {
      app.globalData.imService = new IMService(wx.im);
      app.globalData.imService.connectIM(currentUser);
    }

    let self = this;
    wx.im.on(wx.GoEasyIM.EVENT.CONVERSATIONS_UPDATED, (conversations) => {
      // 设置tabBar未读消息总数以及conversation
      self.setConversations(conversations);
    });
    //加载会话列表
    wx.im.latestConversations()
      .then(res => {
        let content = res.content;
        self.setConversations(content);
        this.setData({
          showLoading: false,
          listShow: true
        })
      })
      .catch(e => {
        console.log(e);
        wx.hideLoading();
      });
  },
  setConversations(conversations) {
    conversations.conversations && conversations.conversations.map((item) => {
      // 格式化时间格式
      item.lastMessage.date = app.formatDate(item.lastMessage.timestamp)
    });
    this.setData({
      conversations: conversations.conversations
    }, () => {
      console.log(this.data.conversations)
    }

    );
    this.setUnreadAmount(conversations.unreadTotal);
  },
  setUnreadAmount(unreadTotal) {
    if (unreadTotal > 0) {
      wx.setTabBarBadge({
        index: 2,
        text: unreadTotal.toString()
      });
    } else {
      wx.hideTabBarRedDot({
        index: 0
      });
    }
  },
  publish: function () {
    var team = this.data.team
    api.team.publish(team).then(res => {
      console.log(res)
    })
  },
  flashComp: function () {
    this.setData({
      activeIndex: !this.data.activeIndex
    })
    this.setData({
      activeIndex: !this.data.activeIndex
    })
  },

  join: function () {
    var teamID = "cbddf0af60696c94008521ae26755d67"
    var leaderID = "oVLKz4g63HfWnc6q8FzZknSV6x-0"
    var params = { teamID, leaderID }
    api.team.apply(params).then(res => {
      console.log(res)
      console.log("join success")
    })
  },
  navbarChange: function (e) {
    var activeIndex = e.detail.index
    this.setData({ activeIndex: activeIndex })

  },
  quit: function () {
    var teamID = "cbddf0af60696c94008521ae26755d67"
    var params = { teamID }
    api.team.quit(params).then(res => {
      console.log(res)
      console.log("quit success")
    })
  },
  accpet: function () {

    var ACID = "79550af2606ab2180d6b9ae9323fc90f"
    var teamID = "cbddf0af60696c94008521ae26755d67"
    var status = 'AC'
    var params = { ACID, teamID, status }
    api.team.accept(params).then(res => {
      console.log(res)
      console.log("ACCCCCCCCCCCCCC")
    })
  },
  tapTeam: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var team = this.data.teams[index]
    var teamID = team._id
    console.log(team)
    wx.navigateTo({
      url: '../detail/detail?team=' + JSON.stringify(team) + '&teamID=' + teamID,
    })
  },
  tapPlayer: function (e) {
    console.log(e)
    var index = e.currentTarget.dataset.index
    var player = this.data.player[index]
    var playerID = player._id
    console.log(player)
    wx.navigateTo({
      url: '../player/player?player=' + JSON.stringify(player) + '&playerID=' + playerID,
    })
  },


  // 分享给朋友
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: '玩转组队'
        })
      }, 2000)
    })
    return {
      title: '玩转组队',
      path: '/pages/contest/index/index',
      promise
    }
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '玩转组队',
      imageUrl: '../../../images/wzhn.jpg'
    }
  }

})

